package com.learn.demo.service.impl;

import com.learn.demo.config.RabbitMQConfig;
import com.learn.demo.service.MessageSender;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageDeliveryMode;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * 延迟消息发送接口实现类
 *
 * @author banjiawei
 * @date 2021/11/23
 */
@Service
@Slf4j
public class MessageSenderImpl implements MessageSender {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Override
    public void sendLazy(Object message) {
        //id + 时间戳 全局唯一
        CorrelationData correlationData = new CorrelationData("9527"+new Date());
        //发送消息时指定 header 延迟时间
        rabbitTemplate.convertAndSend(RabbitMQConfig.LAZY_EXCHANGE, "lazy.boot", message,
                new MessagePostProcessor() {
                    @Override
                    public Message postProcessMessage(Message message) throws AmqpException {
                        log.info(new String(message.getBody()));
                        //设置消息持久化
                        message.getMessageProperties().setDeliveryMode(MessageDeliveryMode.PERSISTENT);
                        //延迟时间毫秒
                        message.getMessageProperties().setDelay(6000);
                        return message;
                    }
                }, correlationData);
    }
}
